﻿// This source is subject to Microsoft Public License (Ms-PL).
// Please see http://taskcardcreator.codeplex.com for details.
// All other rights reserved.

using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Windows;
using System.Windows.Forms;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.ProcessConfiguration.Client;
using Microsoft.TeamFoundation.Server;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using ReportInterface;
using TaskServerServiceInterface;
using Field = Microsoft.TeamFoundation.WorkItemTracking.Client.Field;
using UserControl = System.Windows.Controls.UserControl;

namespace TeamFoundationServer2013Services
{
  [Export(typeof(ITaskServerService))]
  public class Tfs2013 : ITaskServerService
  {
    private ProjectInfo projInfo;
    private WorkItemStore workItemStoreService;
    private WorkItemTypeCollection wiTypes;
    private TeamSettingsConfigurationService teamConfig;
    private Tfs2013UserControl uc;

    public string Name { get { return "Team Foundation Server 2013"; } }

    public bool IsInstalled
    {
      get
      {
        try
        {
          using (var tpp = new TeamProjectPicker(TeamProjectPickerMode.SingleProject, false))
          {
          }
        }
        catch (Exception)
        {
          return false;
        }
        return true;
      }
    }

    public IEnumerable<string> WorkItemTypeCollection
    {
      get
      {
        var list = new List<string>();
        foreach (WorkItemType wiType in wiTypes)
        {
          list.Add(wiType.Name);
        }
        return list;
      }
    }

    public List<ReportItem> WorkItems
    {
      get
      {
        var l = new List<ReportItem>();
        foreach (var w in uc.WorkItems)
        {
          var ri = new ReportItem { Id = w.Id.ToString(), Title = w.Title, Type = w.Type.Name };
          foreach (var relatedLink in w.Links.OfType<RelatedLink>().Where(relatedLink => relatedLink.LinkTypeEnd.Name == "Parent"))
          {
            ri.ParentId = relatedLink.RelatedWorkItemId.ToString();
            break;
          }
          foreach (Field f in w.Fields)
          {
            ri.Fields.Add(f.Name, f.Value);
          }
          l.Add(ri);
        }
        return l;
      }
    }

    public IReport SelectedReport { get { return uc.SelectedReport; } }

    public bool IsProjectSelected { get { return projInfo != null; } }

    public UserControl CreateUserControl(IEnumerable<IReport> reports)
    {
      uc = new Tfs2013UserControl(reports);
      foreach (var teamConfiguration in teamConfig.GetTeamConfigurationsForUser(new[] { projInfo.Uri }))
      {
        uc.Teams.Add(teamConfiguration);
        if (teamConfiguration.IsDefaultTeam)
        {
          uc.SelectedTeam = teamConfiguration;
          uc.SelectedIterationPath = teamConfiguration.TeamSettings.CurrentIterationPath;
        }
      }
      uc.workItemStoreService = workItemStoreService;

      return uc;
    }

    public void OpenProject(Window window)
    {
      using (var tpp = new TeamProjectPicker(TeamProjectPickerMode.SingleProject, false))
      {
        var windowWrapper = new WindowWrapper(new System.Windows.Interop.WindowInteropHelper(window).Handle);
        var result = tpp.ShowDialog(windowWrapper);
        if (result == DialogResult.OK)
        {
          projInfo = tpp.SelectedProjects[0];
          teamConfig = tpp.SelectedTeamProjectCollection.GetService<TeamSettingsConfigurationService>();
          workItemStoreService = tpp.SelectedTeamProjectCollection.GetService<WorkItemStore>();
          foreach (Project project in workItemStoreService.Projects)
          {
            if (project.Name == projInfo.Name)
            {
              wiTypes = project.WorkItemTypes;
              break;
            }
            wiTypes = null;
          }
        }
      }
    }
  }
}
